package persistence

import (
	"context"
	"zxstudy.com/domain/entity"
	"zxstudy.com/infrastructure/ent"
	"zxstudy.com/infrastructure/ent/user"
)

type Users struct {
	client *ent.Client
}

func NewUserRepository(client *ent.Client) *Users {
	return &Users{
		client: client,
	}
}

func (u *Users) Register(ctx context.Context, user *entity.User) (*entity.User, error) {
	newUser, err := u.client.User.
		Create().
		SetName(user.Name).
		SetAge(user.Age).
		Save(ctx)
	if err != nil {
		return nil, err
	}
	
	return newUser.ToDomain(), nil
}

func (u *Users) Update(ctx context.Context, user *entity.User) (*entity.User, error) {
	newUser, err := u.client.User.
		UpdateOneID(user.ID).
		SetName(user.Name).
		SetAge(user.Age).
		Save(ctx)
	if err != nil {
		return nil, err
	}
	return newUser.ToDomain(), nil
}

func (u *Users) Get(ctx context.Context, id int) (*entity.User, error) {
	newUser, err := u.client.User.
		Query().
		Where(user.ID(id)).
		Only(ctx)
	if err != nil {
		return nil, err
	}
	
	return newUser.ToDomain(), err
}

func (u *Users) Users(ctx context.Context) ([]*entity.User, error) {
	users, err := u.client.User.
		Query().
		All(ctx)
	if err != nil {
		return nil, err
	}
	
	newUsers := make([]*entity.User, 0, len(users))
	for _, u := range users {
		newUsers = append(newUsers, u.ToDomain())
	}
	return newUsers, nil
}